package com.weaver.seconddev.api.tl.contract_manage_api;

/**
 * E9原始类路径:com.api.tl.contract_manage_api.NBSContractNextNodeAction
 * JAVA替换说明文档:https://ncnb71xwgeda.feishu.cn/wiki/JLsjwxK8xiHuPIkdu0Dc27Rlnaf?from=from_copylink
 */
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Optional;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import java.util.Map;
import java.util.HashMap;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.interfaces.workflow.action.Action;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 计算下一审批节点
 *
 * @author th
 * @date 2023/10/9 16:01
 */
@org.springframework.stereotype.Service("tl_contract_manage_api_NBSContractNextNodeAction")
public class NBSContractNextNodeAction implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;

    public static final org.slf4j.Logger logger_c21d2d66 = LoggerFactory.getLogger(NBSContractNextNodeAction.class);

    @Resource(name = "tl_contract_manage_api_ContractManageCommon2")
    ContractManageCommon contractManageCommon;

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        RequestInfo requestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        String pushApprovedResult = FAILURE_AND_CONTINUE;
        /* 获取requestId
 TODO 返回值:requestId 存在类型转换风险 e9类型:java.lang.String e9真实类型: int  e10类型:java.lang.String e10真实类型: long */
        String requestId = requestInfo.getRequestid();
        try {
            /* 获取流程ID
 TODO 返回值:workflowId 存在类型转换风险 e9类型:java.lang.String e9真实类型: int  e10类型:java.lang.String e10真实类型: long */
            String workflowId = requestInfo.getWorkflowid();
            // 主表
            String mainTableName = requestInfo.getRequestManager().getBillTableName();
            logger_c21d2d66.info(String.valueOf("RequestId:" + requestId + "======Into NBS Contract Next Node Action======WorkflowId:" + workflowId + ",MainTableName:" + mainTableName));
            // 查询主表数据
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            //String queryMainTableSql = "select fzjdmc,fzspljxtjs from " + mainTableName + " where requestId = ?";
            String queryMainTableSql = "SELECT "+mainTableName+".fzjdmc AS fzjdmc, "+mainTableName+".fzspljxtjs AS fzspljxtjs\n" +
                    "FROM (\n" +
                    "\tSELECT b.*, a.requestid\n" +
                    "\tFROM e10_core_business.wfc_form_data a, e10_core_business."+mainTableName+" b\n" +
                    "\tWHERE a.dataid = b.form_data_id\n" +
                    "\t\tAND a.delete_type = 0\n" +
                    "\t\tAND a.tenant_key = 'tl2k2r96ty'\n" +
                    ") "+mainTableName+"\n" +
                    "WHERE "+mainTableName+".requestid = ?\n" +
                    "\tAND "+mainTableName+".delete_type = 0\n" +
                    "\tAND "+mainTableName+".tenant_key = 'tl2k2r96ty'";
            logger_c21d2d66.info(String.valueOf("Execute Sql:" + queryMainTableSql));
            String poolname = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            rs.executeQuery(queryMainTableSql, poolname, requestId);
            CalculateContractNextNodeReq calculateContractNextNodeReq = new CalculateContractNextNodeReq();
            List<ContractApprovalHierarchyInfo> approvalHierarchyInfoList = null;
            String base64DOAResult = null;
            String nodeNameId;
            if (rs.next()) {
                base64DOAResult = rs.getString("fzspljxtjs");
                nodeNameId = rs.getString("fzjdmc");
            } else {
                nodeNameId = null;
            }
            logger_c21d2d66.info(String.valueOf("base64DOAResult:" + base64DOAResult + ",nodeNameId:" + nodeNameId));
            if (StringUtils.isNotBlank(base64DOAResult)) {
                approvalHierarchyInfoList = JSON.parseObject(new String(java.util.Base64.getDecoder().decode(base64DOAResult)), new TypeReference<List<ContractApprovalHierarchyInfo>>() {
                });
            }
            logger_c21d2d66.info(String.valueOf("approvalHierarchyInfoList:" + approvalHierarchyInfoList));
            // 获取当前节点ID
            String currentNodeId = null;
            if (StringUtils.isNotBlank(nodeNameId)) {
                Optional<ContractApprovalHierarchyInfo> optionalInfo = approvalHierarchyInfoList.stream().filter(info -> nodeNameId.equals(info.getNodeName())).findFirst();
                if (optionalInfo.isPresent()) {
                    currentNodeId = optionalInfo.get().getNodeId();
                }
            }
            logger_c21d2d66.info(String.valueOf("currentNodeId:" + currentNodeId));
            calculateContractNextNodeReq.setRequestId(requestId);
            calculateContractNextNodeReq.setCurrentNodeId(currentNodeId);
            calculateContractNextNodeReq.setApprovalHierarchyInfoList(approvalHierarchyInfoList);
            logger_c21d2d66.info(String.valueOf("calculateContractNextNodeReq:" + calculateContractNextNodeReq));
            String nextApprovalNodeId = contractManageCommon.calculationNextApprovalNode(calculateContractNextNodeReq);
            if (StringUtils.isNotBlank(nextApprovalNodeId)) {
                //String updateSql = "update " + mainTableName + " set xyjd = ? where requestId = ?";
                String updateSql = "UPDATE (\n" +
                        "\tSELECT b.*, a.requestid\n" +
                        "\tFROM e10_core_business.wfc_form_data a, e10_core_business."+mainTableName+" b\n" +
                        "\tWHERE a.dataid = b.form_data_id\n" +
                        "\t\tAND a.delete_type = 0\n" +
                        "\t\tAND a.tenant_key = 'tl2k2r96ty'\n" +
                        ") "+mainTableName+"\n" +
                        "SET "+mainTableName+".xyjd = ?\n" +
                        "WHERE form_data_id IN (\n" +
                        "\t\tSELECT dataid AS dataid\n" +
                        "\t\tFROM e10_core_business.wfc_form_data\n" +
                        "\t\tWHERE "+mainTableName+".requestid = ?\n" +
                        "\t\t\tAND wfc_form_data.delete_type = 0\n" +
                        "\t\t\tAND wfc_form_data.tenant_key = 'tl2k2r96ty'\n" +
                        "\t)\n" +
                        "\tAND "+mainTableName+".delete_type = 0\n" +
                        "\tAND "+mainTableName+".tenant_key = 'tl2k2r96ty'";
                logger_c21d2d66.info(String.valueOf("Execute Sql:" + updateSql + ",xyjd:" + nextApprovalNodeId + ",requestId:" + requestId));
                String poolname_ij = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                rs.executeUpdate(updateSql, poolname_ij, nextApprovalNodeId, requestId);
                pushApprovedResult = SUCCESS;
            }
        } catch (Exception e) {
            logger_c21d2d66.error(e.getMessage());
        }
        logger_c21d2d66.info(String.valueOf("RequestId:" + requestId + "======Out NBS Contract Next Node Action======ReturnResult:" + pushApprovedResult));
        return WeaResult.success(getResultMapForAction(weaverResultMap, "result", pushApprovedResult, requestInfo.getRequestManager()));
    }

    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }
}
